<script setup lang="ts">
import { getCurrentInstance, onMounted, ref, watch } from 'vue'
import EditTable from '@/views/project-update/library-manage/edit-table.vue'
import CommonLayoutTable from '@/views/project-update/library-manage/common-layout-table.vue'
import {
  buildRenderTables,
  investRenderTables,
  operationRenderTables,
} from '@/views/project-update/library-manage/edit-table-info'
import { Message, MessageBox } from 'element-ui'
import {
  projectStageAddOrUpdate,
  projectStageQuery,
  projectStageDelete,
} from '@/api/project-update/stage-info'
import {
  updatePeStage,
  updateProject,
} from '@/api/project-update/project-inventory'

const vm = getCurrentInstance()

const userLevel = JSON.parse(localStorage.getItem('user') || '{}')?.user
  ?.roleLevel

const route = vm.proxy.$route
const router = vm.proxy.$router
const currentUser = vm.proxy.$store.state.user.currentUser

const params = route.query
const { pkid, es: status, status: applyStatus } = params

const handleCancel = () => {
  router.go(-1)
}

const checkedStage = ref('实施阶段')

const stageList = ref([
  {
    label: '实施阶段',
    value: '实施阶段',
  },
  {
    label: '运营阶段',
    value: '运营阶段',
  },
])

const editableTabs = ref([])

const editableOperateTabs = ref([])

const implementStageInfoList = ref([])
const manageStageInfoList = ref([])

const editableTabsValue = ref('')

const editableOperateTabsValue = ref('')

const deleteStageArr = ref([])

const handleAddTab = () => {
  MessageBox.prompt('请输入阶段所在年份', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[0-9]{4}$/,
    inputErrorMessage: '请输入年份',
  }).then(({ value }) => {
    if (checkedStage.value === '实施阶段') {
      if (editableTabs.value.some((item) => item.name == value)) {
        Message.warning('该年份已存在')
        return
      }
      editableTabs.value.push({
        title: value,
        name: value,
      })
      editableTabsValue.value = value
    } else {
      if (editableOperateTabs.value.some((item) => item.name == value)) {
        Message.warning('该年份已存在')
        return
      }
      editableOperateTabs.value.push({
        title: value,
        name: value,
      })
      editableOperateTabsValue.value = value
    }
  })
}

const handleRemoveTab = (targetName) => {
  const pkid = implementStageInfoList.value.find(
    (i) => i.year == targetName
  )?.pkid
  if (pkid) {
    deleteStageArr.value.push({
      type: 'implement',
      pkid: pkid,
    })
  }

  if (editableTabs.value.length === 1) {
    // Message.warning('至少保留一个阶段')
    editableTabsValue.value = ''
    editableTabs.value = []
    implementStageInfoList.value = []
    getFormData()
    return
  }
  const tabs = editableTabs.value
  let activeName = editableTabsValue.value
  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.name === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeName = nextTab.name
        }
      }
    })
  }

  editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
  implementStageInfoList.value = implementStageInfoList.value.filter(
    (item) => item.year != targetName
  )
  // manageStageInfoList.value = manageStageInfoList.value.filter(
  //   (item) => item.year != targetName
  // )
  editableTabsValue.value = activeName
}

const handleRemoveOperateTab = (targetName) => {
  const pkid = manageStageInfoList.value.find((i) => i.year == targetName)?.pkid
  if (pkid) {
    deleteStageArr.value.push({
      type: 'manage',
      pkid: pkid,
    })
  }

  if (editableOperateTabs.value.length === 1) {
    // Message.warning('至少保留一个阶段')
    editableOperateTabsValue.value = ''
    editableOperateTabs.value = []
    manageStageInfoList.value = []
    getFormOperateData()
    return
  }

  const tabs = editableOperateTabs.value
  let activeName = editableOperateTabsValue.value
  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.name === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeName = nextTab.name
        }
      }
    })
  }

  editableOperateTabs.value = tabs.filter((tab) => tab.name !== targetName)
  // implementStageInfoList.value = implementStageInfoList.value.filter(
  //   (item) => item.year != targetName
  // )
  manageStageInfoList.value = manageStageInfoList.value.filter(
    (item) => item.year != targetName
  )
  editableOperateTabsValue.value = activeName
}

const buildTableRef = ref(null)
const projectTableRef = ref(null)
const manageTableRef = ref(null)

const getDetail = () => {
  projectStageQuery({ projectId: pkid })
    .then((res) => {
      if (res.success) {
        if (res.data) {
          const { implementStageInfoList: iL, manageStageInfoList: mL } =
            res.data
          implementStageInfoList.value = iL
          manageStageInfoList.value = mL
          editableTabs.value = []
          editableTabsValue.value = ''
          if (iL.length) {
            iL.forEach((item) => {
              if (item.year) {
                editableTabs.value.push({
                  title: item.year?.toString(),
                  name: item.year?.toString(),
                })
              }
            })
            editableTabsValue.value = iL[0].year.toString()
          }
          
          editableOperateTabs.value = []
          editableOperateTabsValue.value = ''
          if (mL.length) {
            mL.forEach((item) => {
              if (item.year) {
                editableOperateTabs.value.push({
                  title: item.year?.toString(),
                  name: item.year?.toString(),
                })
              }
            })
            editableOperateTabsValue.value = mL[0].year.toString()
          }
          
        } else {
          editableTabsValue.value = ''
          editableTabs.value = []
          editableOperateTabsValue.value = ''
          editableOperateTabs.value = []
        }
      } else {
        Message.error(res.message)
      }
    })
    .catch((err) => {
      // editableTabsValue.value = '2024'
      // editableTabs.value = [
      //   {
      //     title: '2024',
      //     name: '2024',
      //   },
      // ]
      // editableTabsValue.value = ''
      // editableTabs.value = []
      // editableOperateTabsValue.value = ''
      // editableOperateTabs.value = []
    })
}

onMounted(() => {
  getDetail()
})

const getFormData = () => {
  const currentYear = editableTabsValue.value
  const iF =
    implementStageInfoList.value.find((item) => item.year == currentYear) || {}
  // const mF =
  //   manageStageInfoList.value.find((item) => item.year == currentYear) || {}
  buildTableRef.value?.inputData(iF)
  projectTableRef.value?.inputData(iF)
  // manageTableRef.value?.inputData(mF)
}

const getFormOperateData = () => {
  const currentYear = editableOperateTabsValue.value
  // const iF =
  //   implementStageInfoList.value.find((item) => item.year == currentYear) || {}
  const mF =
    manageStageInfoList.value.find((item) => item.year == currentYear) || {}
  // buildTableRef.value?.inputData(iF)
  // projectTableRef.value?.inputData(iF)
  manageTableRef.value?.inputData(mF)
}

watch(
  () => editableTabsValue.value,
  (newVal, oldVal) => {
    if (oldVal) {
      const buildData = buildTableRef.value?.getSubmitForm()
      const projectData = projectTableRef.value?.getSubmitForm()
      // const manageData = manageTableRef.value?.getSubmitForm()
      const iIndex = implementStageInfoList.value.findIndex(
        (item) => item.year == oldVal
      )
      if (iIndex > -1) {
        const iF = implementStageInfoList.value[iIndex]
        Object.assign(iF, {
          ...buildData,
          ...projectData,
        })
      }
      // const mIndex = manageStageInfoList.value.findIndex(
      //   (item) => item.year == oldVal
      // )
      // if (mIndex > -1) {
      //   const mF = manageStageInfoList.value[mIndex]
      //   Object.assign(mF, manageData)
      // }
    }
    if (newVal) {
      getFormData()
    } else {
      // manageStageInfoList.value = []
      implementStageInfoList.value = []
    }
  }
)

watch(
  () => editableOperateTabsValue.value,
  (newVal, oldVal) => {
    if (oldVal) {
      // const buildData = buildTableRef.value?.getSubmitForm()
      // const projectData = projectTableRef.value?.getSubmitForm()
      const manageData = manageTableRef.value?.getSubmitForm()
      // const iIndex = implementStageInfoList.value.findIndex(
      //   (item) => item.year == oldVal
      // )
      // if (iIndex > -1) {
      //   const iF = implementStageInfoList.value[iIndex]
      //   Object.assign(iF, {
      //     ...buildData,
      //     ...projectData,
      //   })
      // }
      const mIndex = manageStageInfoList.value.findIndex(
        (item) => item.year == oldVal
      )
      if (mIndex > -1) {
        const mF = manageStageInfoList.value[mIndex]
        Object.assign(mF, manageData)
      }
    }
    if (newVal) {
      getFormOperateData()
    } else {
      manageStageInfoList.value = []
      // implementStageInfoList.value = []
    }
  }
)

const editTableRef = ref()

const saveProjectInfo = () => {
  const data = editTableRef.value?.getSubmitData()
  updateProject(
    {},
    {
      id: pkid,
      ...data,
    }
  ).then((res) => {
    if (res.success) {
      //
    } else {
      Message.error(res.message)
    }
  })
}

const handleSaveClick = async () => {
  const buildData = buildTableRef.value?.getSubmitForm()
  const projectData = projectTableRef.value?.getSubmitForm()
  const manageData = manageTableRef.value?.getSubmitForm()
  if (
    (!areAllPropertiesEmpty(buildData) ||
      !areAllPropertiesEmpty(projectData)) &&
    (editableTabsValue.value === '0' || editableTabsValue.value === '')
  ) {
    Message.warning('请填写实施阶段年份')
    return
  }

  if (
    !areAllPropertiesEmpty(manageData) &&
    (editableOperateTabsValue.value === '0' ||
      editableOperateTabsValue.value === '')
  ) {
    Message.warning('请填写运营阶段年份')
    return
  }

  let iF = implementStageInfoList.value.find(
    (item) => item.year == editableTabsValue.value
  )
  if (!iF) {
    iF = {
      year: editableTabsValue.value,
      projectId: pkid,
    }
    implementStageInfoList.value.push(iF)
  }
  Object.assign(iF, {
    ...buildData,
    ...projectData,
  })
  let mF = manageStageInfoList.value.find(
    (item) => item.year == editableOperateTabsValue.value
  )
 
  if (!mF) {
    mF = {
      year: editableOperateTabsValue.value,
      projectId: pkid,
    }
    manageStageInfoList.value.push(mF)
  }
  Object.assign(mF, manageData)
  
  // 实施阶段数据为空
  if (editableTabs.value.length === 0 && areAllPropertiesEmpty(buildData) && areAllPropertiesEmpty(projectData)) {
    implementStageInfoList.value = []
  }
  
  // 运营阶段数据为空
  if (editableOperateTabs.value.length === 0 && areAllPropertiesEmpty(manageData)) {
    manageStageInfoList.value = []
  }

  const submitData = {
    projectId: pkid,
    implementStageInfoList: implementStageInfoList.value,
    manageStageInfoList: manageStageInfoList.value,
  }

  try {
    let deleteArr = []
    for (let del of deleteStageArr.value) {
      const delRes = await projectStageDelete(del)
      if (delRes.success) {
        deleteArr.push(delRes)
      }
    }
    
    saveProjectInfo()
    if (deleteArr.length === deleteStageArr.value.length) {
      await projectStageAddOrUpdate(submitData).then((res) => {
        if (res.success) {
          Message.success('保存成功')
          router.go(-1)
        } else {
          Message.error(res.message)
        }
      })
    } else {
      Message.error('保存失败')
    }
  } catch (error) {
    console.log('error', error)
  }
}

// 判断表单是否填写
const areAllPropertiesEmpty = (obj: Object) => {
  for (let key in obj) {
    if (
      Object.prototype.hasOwnProperty.call(obj, key) &&
      obj[key] !== null &&
      obj[key] !== undefined &&
      obj[key] !== ''
    ) {
      return false
    }
  }
  return true
}
</script>

<template>
  <div class="add-month-report show-detail-form">
    <div class="nav">
      <div class="breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/project-update/library-manage' }"
            ><span class="breadcrumb-title">列表</span></el-breadcrumb-item
          >
          <el-breadcrumb-item>编辑</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    <div class="content">
      <div class="content-main">
        <edit-table
          ref="editTableRef"
          :pkid="pkid"
          :disabled="!!status"
          :user-level="userLevel"
        />
        <div class="stage-select">
          <el-radio-group v-model="checkedStage">
            <el-radio-button
              v-for="stage in stageList"
              :key="stage.value"
              :label="stage.value"
            ></el-radio-button>
          </el-radio-group>
          <el-tabs
            editable
            v-model="editableTabsValue"
            @tab-add="handleAddTab"
            @tab-remove="handleRemoveTab"
            v-show="checkedStage === '实施阶段'"
          >
            <el-tab-pane
              :key="item.name"
              v-for="item in editableTabs"
              :label="item.title"
              :name="item.name"
            >
            </el-tab-pane>
          </el-tabs>
          <el-tabs
            editable
            v-model="editableOperateTabsValue"
            @tab-add="handleAddTab"
            @tab-remove="handleRemoveOperateTab"
            v-show="checkedStage === '运营阶段'"
          >
            <el-tab-pane
              :key="item.name"
              v-for="item in editableOperateTabs"
              :label="item.title"
              :name="item.name"
            >
            </el-tab-pane>
          </el-tabs>
          <div class="new-add">新增年份</div>
        </div>
        <div class="stage-detail-table" v-show="checkedStage === '实施阶段'">
          <div class="common-title">
            <i class="title-icon"></i>
            <span>项目建设情况</span>
          </div>
          <common-layout-table
            :render-tables="buildRenderTables"
            ref="buildTableRef"
          />
          <div class="common-title">
            <i class="title-icon"></i>
            <span>项目投资情况</span>
          </div>
          <common-layout-table
            :render-tables="investRenderTables"
            ref="projectTableRef"
          />
        </div>
        <div class="stage-detail-table" v-show="checkedStage === '运营阶段'">
          <div class="common-title">
            <i class="title-icon"></i>
            <span>项目运营情况</span>
          </div>
          <common-layout-table
            :render-tables="operationRenderTables"
            ref="manageTableRef"
          />
        </div>
      </div>
      <div class="buttons">
        <el-button class="cancel" @click="handleCancel">取消</el-button>

        <el-button class="save" type="primary" @click="handleSaveClick"
          >保存</el-button
        >
        <!--        <el-button class="publish" @click="handleSaveClick(1)">提交</el-button>-->
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.add-month-report {
  width: calc(100% - 40px);
  height: calc(100% - 40px);
  padding: 20px;
  background-color: rgba(244, 248, 254, 1);

  .content {
    width: calc(100% - 40px);
    height: calc(100% - 70px);
    position: absolute;
    top: 65px;
    bottom: 0;

    .divider {
      width: 100%;
      height: 1px;
      background: #e7f0ff;
      border-radius: 1px 1px 0px 0px;
      margin: 20px 0;
    }

    .content-main {
      height: calc(100% - 100px);
      background: #ffffff;
      box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1);
      border-radius: 2px;
      padding: 13px 16px 13px 16px;
      overflow-y: auto;

      .common-title {
        margin: 10px 0;
        padding: 0px 0 2px 5px;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: bold;
        color: #000000;
        display: flex;
        align-items: center;

        > span {
          margin-left: 5px;
        }

        .title-icon {
          width: 5px;
          height: 16px;
          background: #10a6dd;
          border-radius: 3px;
          margin-right: 4px;
        }
      }

      .stage-select {
        margin-top: 20px;
        display: flex;
        align-items: center;

        .el-radio-group {
          margin-right: 20px;
        }

        .new-add {
          color: rgba(0, 0, 0, 0.5);
          font-size: 14px;
          margin-left: 10px;
        }
      }

      :deep(.el-tabs) {
        height: 100%;

        .el-tabs__content {
          height: calc(100% - 60px);

          .el-tab-pane {
            padding: 0;
            height: 100%;
            overflow-y: auto;
          }

          .basetable-content {
            padding: 0 !important;

            .el-table {
              margin-top: 0 !important;
              height: 100%;
            }
          }

          .basetable-footer {
            bottom: 0;
            margin: 0;
          }
        }
      }
    }

    .buttons {
      padding: 10px;
      display: flex;
      justify-content: center;
      background: #ffffff;
      box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.1);

      .el-button {
        width: 110px;
      }

      .cancel {
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #e7f0ff;
        font-weight: 400;
        font-size: 16px;
        color: #8894a8;
      }

      .save {
        //background: #10a6dd;
        border-radius: 4px;
        //color: #ffffff;
      }

      .publish {
        //background: #ffffff;
        border-radius: 4px;
        //color: #10a6dd;
        //border: 1px solid #10a6dd;
      }
    }
  }
}
</style>
